<?php

class RegisterModel extends Model
{
	public function __construct()
	{
		parent::__construct();
		
		$playerName = Input::request("name");
		$pass = Input::request("password");
		$repPass = Input::request("repeat_password");
		$mail = strtolower(Input::request("mail"));
		
		if (preg_match(PATTERN_PLAYER_NAME, $playerName) !== 1)
			$this->addError("name", "PLAYER_NAME_ERROR");
		// Проверяем почту на правильность
		if (preg_match(PATTERN_MAIL, $mail) !== 1)
			$this->addError("mail", "MAIL_ERROR");
		$passLen = strlen($pass);
		if ($passLen < 3 || $passLen > 16)
			$this->addError("password", "PASSWORD_ERROR");
		else if ($pass != $repPass)
			$this->addError("repeat_password", "REPEAT_PASSWORD_ERROR");
		
		$pr = PlayerRegistry::i();
		
		// Проверка на совпадения
		if (!$this->hasError())
		{			
			if (!is_null($pr->byMail($mail)))
				$this->addError("mail", "MAIL_USED_ERROR");
			if (!is_null($pr->byName($playerName)))
				$this->addError("name", "PLAYER_NAME_USED_ERROR");
		}
		
		// Если всё хорошо, создаём игрока и перенаправляем пользователя на страницу входа
		if (!$this->hasError())
		{
			$fields = array
			(
				"name" => $playerName, "mail" => $mail, "raw_password" => $pass,
				"ac_level" => Access::PLAYER, "gold" => "100", "about" => "",
				"register_date" => time(),
			);
			
			$pr->add(new PlayerObject($fields));
			//PlayerMapper::create($playerName, $mail, $pass);
			header("Location: /?view=login&pattern=reg_complete&login=" . $playerName);
			die();
		}
	}
	
}

?>